package com.example.demo.interceptor;

import com.example.demo.utils.SysUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器，判断用户的登录状态，并封装传递给controller目标对象
 */
@Slf4j
//@Component
public class TestInterceptor implements HandlerInterceptor {

    /**
     * 在目标方法执行之前
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

      /*  System.out.println(StringUtils.center("测试 拦截器", 30));
        String servletPath = request.getServletPath();
        log.info("servletPath={}", servletPath);*/

        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
           /*     Stream<Cookie> cookieStream = Arrays.stream(cookies).filter((cookie -> {
                    return cookie.getName().equals(SysUtils.TEMP_COOKIE_NAME);
                }));*/
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                log.info("cookie name={} |value={}", cookie.getName(), cookie.getValue() + "<|>" + cookie.getDomain());
                if (name.equals(SysUtils.TEMP_USER_COOKIE_NAME)) {
                    //cookie.getMaxAge()总是-1|https://www.cnblogs.com/liqing-weikeyuan/p/8192768.html
                    // System.out.println("cookie max ageis " + cookie.getMaxAge());
                    break;
                }
            }
        }
        return true;
    }
}

